<template>
  <base-breadcrumb
    class="UpdateDesignPlanCollect-container fixed-container"
    :title="breadcrumbTitle"
    v-loading="loadingState.isDetail"
    :breadcrumb="!isAudit"
  >
    <a-card>
      <title-name :title="breadcrumbTitle" />
      <custom-form
        ref="ruleForm"
        :rules="rules"
        :isValidate="true"
        :form-list="formItemList"
        :form="formInfo"
        :edit-model="pageType === 'look' ? 'V' : ''"
        :is-emit="false"
        @selectOrg="selectOrg"
        @getProjectInfo="getProjectInfo"
      />
    </a-card>
    <a-card>
      <div class="upload-wrapper" v-for="item in uploadTableList" :key="item.key">
        <div class="title-wrapper">
          <title-name :title="item.title">
            <template v-if="isDisabled">
              <span>{{ item.title.replace('上传', '') }}</span>
            </template>
            <template v-else>
              <span v-if="item.required">{{ item.title }}（<span style="color: red">必传项</span>）</span>
            </template>
          </title-name>
        </div>
        <UploadTableNew
          :ref="`${item.key}-uploadTable`"
          :disabled="isDisabled"
          business-code="DESIGN02"
          :mode="pageType"
          :needPage="false"
          :initFileList="pageType === 'add' ? null : (formInfo[item.key] || []) "
          :useMultiDelete="true"
        />
      </div>
    </a-card>
    <div v-if="!isConsultation" class="tool-btns tool-btns--fixed page-btn-right-top">
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="loadingState.DRAFT"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="loadingState.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button class="ml12" type="default" @click="handleClose"> 关闭 </a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import Moment from 'moment'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import { addData, updateData, getDetail } from '@/api/design/deepDesign/planningDataCollect'

const uploadTableList = [
  {
    key: 'designResultsMaterialFileList',
    title: '阶段性设计成果相关资料上传',
    required: true
  },
  {
    key: 'designGeologicalExplorationMaterialFileList',
    title: '地勘相关资料上传',
    required: true
  },
  {
    key: 'designProfitLossMaterialFileList',
    title: '商务盈亏分析（导向分析）相关资料上传',
    required: true
  },
  {
    key: 'designProcurementMaterialFileList',
    title: '采购价差清单（导向分析）相关资料上传',
    required: true
  },
  {
    key: 'designAssignmentBookMaterialFileList',
    title: '设计任务书相关资料上传',
    required: true
  },
  {
    key: 'designConstructionMaterialFileList',
    title: '施工重难点相关资料上传'
  },
  {
    key: 'designResearchReportMaterialFileList',
    title: '可行性研究报告相关资料上传'
  },
  {
    key: 'designTechnologyMaterialFileList',
    title: '甲方技术标准相关资料上传'
  },
  {
    key: 'designTbluePrintMaterialFileList',
    title: '设计出图计划表相关资料上传'
  }
]

export default {
  name: 'UpdateDesignPlanCollect',
  data() {
    return {
      formInfo: {
        designCategoryName: '',
        viewName: ""
      },
      uploadTableList: uploadTableList,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增设计策划资料',
        edit: '编辑设计策划资料',
        look: '查看设计策划资料'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: this.pageType === 'add',
          isNeedAuth:true,
          checkStrictly: true,
          disabled: this.isDisabled,
          isQueryProjecDetail: !this.isDisabled,
          isNoBorder: this.isDisabled,
          viewName: "viewName",
        },
        // {
        //   label: '分公司',
        //   keyName: 'branchComId',
        //   viewName: 'branchComName',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.pageType === 'add'
        //   },
        //   disabled: this.isDisabled,
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectId',
        //   viewName: 'projectName',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.pageType === 'add',
        //     keyValue: 'branchComId',
        //     isEdit: true,
        //     form: this.formInfo
        //   },
        //   selectChange: (e) => {
        //     this.formInfo.designCategoryId = e.$origin?.designTypeId
        //     this.formInfo.designCategoryName = e.$origin?.designTypeName
        //   },
        //   disabled: this.isDisabled,
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }]
        // },
        {
          label: '项目设计管理类别',
          keyName: 'designCategoryName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '设计策划资料名称',
          keyName: 'materialName',
          type: 'BaseInput',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入设计策划资料名称', trigger: 'change' }]
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '资料内容描叙',
          keyName: 'materialContent',
          type: 'BaseTextarea',
          disabled: this.isDisabled,
          span: 24,
          attrs: {
            maxLength: 3000
          }
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    }
  },
 async created() {
    this.initPage()
    this.getDetailReq()
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('design_plan_material_audit')
  },
  methods: {
    selectOrg(val) {
      this.formInfo.branchComId = val[val.length - 2].orgId
    },
    getProjectInfo(info) {
          this.formInfo.designCategoryId = info.designId
          this.formInfo.designCategoryName = info.designName
          this.$forceUpdate()
    },
    /**
     * 获取详情
     */
    async getDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data
        }
        this.formInfo.viewName = this.formInfo.branchComName + '/' + this.formInfo.projectName
        // 取出对应文件列表的fileInfoVO对象
        this.uploadTableList.forEach((item) => {
          this.formInfo[item.key] = (res.data[item.key] && res.data[item.key].map((file) => file.fileInfoVO)) || []
        })
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    handleClose() {
      this.$close()
    },
    /**
     * 初始化页面数据
     */
    initPage() {
      // 新增时，生成创建人和创建时间
      if (this.pageType === 'add') {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        this.formInfo = {
          ...this.formInfo,
          creatorName: userInfo.name,
          createTime: curDate
        }
      }
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
              this.$message.warning("请填写完所有必填项信息")
            return}
          this.submitApprovalConfirm(this.processConfig,(flag)=>{
            if(!flag) {
              return
            }
            this.invokeSave(actionName)
          })
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      this.setProcessConfig = null;
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const params = {
          ...this.formInfo,
          materialStatus: actionName === 'DRAFT' ? 0 : 1 // 0：保存草稿/1：提交审批/2：审批通过/3：审批不通过
        }
        this.uploadTableList.forEach((item) => {
          const ref = this.$refs[`${item.key}-uploadTable`] && this.$refs[`${item.key}-uploadTable`][0]
          params[item.key] = ref.getChangedFileIds().allList.map((id) => {
            return { fileId: id }
          })
          // 提交时，校验文件必填项
          if (actionName === 'SUBMITTED' && !params[item.key].length && item.required) {
            this.$message.warning(`${item.title.replace('上传', '还未上传')}`)
            throw new Error(`${item.key} is required`)
          }
        })
        const fn = this.pageType === 'add' ? addData : updateData
        await fn(params).then((res)=>{
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        if(actionName =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
            this.handleClose()
          }
        })

        this.uploadTableList.forEach((item) => {
          const ref = this.$refs[`${item.key}-uploadTable`] && this.$refs[`${item.key}-uploadTable`][0]
          ref.batchDeleteFile() // 删除之前记录下的待删除文件
        })
        this.loadingState[actionName] = false
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.upload-wrapper {
  padding-bottom: 40px;
}
</style>
